<template>
    <van-config-provider :theme="theme" class="main">
        <van-nav-bar title="登录"></van-nav-bar>
        <van-button type="primary" size="mini" @click="changeTheme" class="btn"
            color="linear-gradient(to right, #ff8030, #FFC0CB)">切换主题</van-button>
        <van-form @submit="onSubmit">
            <van-cell-group inset>
                <van-field required v-model="loginname" name="loginname" label="用户名" placeholder="用户名"
                    :rules="[{ pattern: loginnamePattern, message: '请填写用户名-至少三位-数字字母下划线组成' }]" />
                <van-field required v-model="password" type="password" name="password" label="密码" placeholder="密码"
                    :rules="[{ pattern: passwordPattern, message: '请填写密码-至少三位' }]" />
            </van-cell-group>
            <div style="margin: 16px;">
                <van-button type="primary" size="normal" native-type="submit" style="margin:10px 8px; width: 45%;"
                    color="linear-gradient(to right, #ff8030, #FFC0CB)">
                    登录
                </van-button>
                <van-button type="primary" size="normal" to="regist" style="margin:10px 8px; width: 45%;"
                    color="linear-gradient(to right, #ff8030, #FFC0CB)">去注册</van-button>
            </div>
        </van-form>
    </van-config-provider>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { login } from '../api/user'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/userStore'
let router = useRouter();
let userStore = useUserStore();

let theme = ref('');
let flag = ref(true);
let loginname = ref('');
let password = ref('');
const loginnamePattern = /^\w{3,}$/;
const passwordPattern = /^.{3,}$/;
let onSubmit = function (values: any) {
    console.log('submit', values);
    login(values.loginname, values.password).then(res => {
        console.log(res);
        if (res.data.code == 200) {
            alert(res.data.message);
            userStore.token = res.data.data.token;
            userStore.userid = res.data.data.userid;
            userStore.loginname = values.loginname;
            router.push("/home");
        } else {
            alert(res.data.message);
        }
    });
}
// 主题切换
let changeTheme = function () {
    flag.value = !flag.value;
    if (flag.value) {
        theme.value = 'light';
    } else {
        theme.value = 'dark';
    }
}

</script>

<style lang="scss" scoped>
.btn {
    margin: 10px 10px 100px
}

.main {
    margin: 0 auto;
    height: 100vh;
    background-image: url("@/assets/img/image.png");
}
</style>
